import { defineStore } from 'pinia'

interface ILoading {
  // 加载状态是否启用
  loading: boolean
  loadingText: string
}

const NORMAL_LOADING_TEXT = '系统加载中，请稍候...'
const UPLOAD_LOADING_TEXT = '文件解析中，请稍候...'
const ACTION_RENAME_TEXT = '重命名执行中，请勿占用文件...'

const useGlobalLoadingStateStroe = defineStore('globalLoadingState', {
  state(): ILoading {
    return {
      loading: false,
      loadingText: NORMAL_LOADING_TEXT
    }
  },
  actions: {
    async start(
      callback: (...arg: any[]) => Promise<any> | any,
      loadingText: string
    ) {
      this.loading = true
      this.loadingText = loadingText
      try {
        await callback()
      } finally {
        setTimeout(() => {
          this.loading = false
        }, 500)
      }
    },
    async parseFile(callback: (...arg: any[]) => Promise<any> | any) {
      await this.start(callback, UPLOAD_LOADING_TEXT)
    },
    async systemLoading(callback: (...arg: any[]) => Promise<any> | any) {
      await this.start(callback, NORMAL_LOADING_TEXT)
    },
    async actionRename(callback: (...arg: any[]) => Promise<any> | any) {
      await this.start(callback, ACTION_RENAME_TEXT)
    }
  }
})

export default useGlobalLoadingStateStroe
